<?php


namespace api\home\controller;


use api\home\model\SmsModel;
use api\home\model\UserModel;
use api\home\validata\UserValidata;
use cmf\controller\RestBaseController;
use think\facade\Filesystem;
use think\Request;

class UserController extends RestBaseController
{

    //发送验证码
    public function sendcode()
    {
        $mobile = input('mobile');
        //发验证码
        sendAliSms($mobile);
    }

    //注册
    public function register()
    {

        //接收参数
        $data = input('post.');

        //验证器验证
        $validate = new UserValidata();
        $result = $validate->scene('register')->check($data);
        if(!$result){
            $this->error($validate->getError());
        }

        // 验证用户是否存在
        $user = UserModel::where('mobile','=',$data['mobile'])->find();
        if($user){
            $this->error('用户已存在');
        }

        //验证码验证
        checkSms($data['mobile'], $data['code']);

        //添加
        if(UserModel::create($data)){
            $this->success('注册成功');
        }else{
            $this->error('注册失败');
        }

    }

    //登录
    public function login()
    {
        $mobile = input('mobile');
        $code = input('code');

        if(empty($mobile)){
            $this->error('电话不存在');
        }
        if(empty($code)){
            $this->error('验证码不存在');
        }

        $data = UserModel::where('mobile','=',$mobile)->find();
        if(empty($data)){
            $this->error('手机号错误');
        }

        $sms = SmsModel::where('mobile','=',$mobile)->find();
        //halt($sms);

        if(checkSms($mobile, $sms['code'])){
            $token = signToken($data['id'],$mobile);
            $this->success(
                '登陆成功',
                [
                    'data' => $token
                ]
            );
        }else{
            $this->error('登录失败');
        }

    }

    //用户列表显示
    public function getUserList()
    {

        $user = UserModel::order('id','DESC')
            ->select();

        $this->success('用户列表',$user);
    }



    //修改个人信息
    public function updateUser()
    {
        //获取信息
        $data = input('post.');

        //验证查询信息
        $edit = UserModel::find($data['id']);
        if(!$edit){
            $this->error('未查询到信息');
        }
        //修改信息
        $edit->name = $data['name'];
        $edit->image = $data['image'];
        $edit->mobile = $data['mobile'];
        if($edit->save()){
            $this->success('修改成功');
        }else{
            $this->error('修改失败');
        }
    }


}